package org.mao.forumtest;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.google.common.collect.Lists;

public class ReadLwgodPost {

	private final static Logger logger;

	static {
		PropertyConfigurator.configure("D:/workspace/spiderman/src/main/resources/conf/log4j.properties");// 加载.xml文件
		logger = Logger.getLogger(ReadLwgodPost.class);
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		logger.info("go");
		ReadLwgodPost read = new ReadLwgodPost();
		try {
			// read.readHomePage("http://www.lwgod.com/thread-593762-1-33.html");
			// read.readHomePageTxt("G:/download/lwgod/post.txt", "http://www.lwgod.com/thread-815833-1-1.html");
			read.readHomePageTxt("G:/download/lwgod/post.txt", "");
			// read.readHomePageTxt("", "http://www.lwgod.com/thread-815833-1-1.html");
		} catch (Exception e) {
			logger.error("", e);
		}
	}

	public void readHomePage(String url) throws Exception {
		File file = new File("G:/download/lwgod/post.txt");
		if (!file.getParentFile().exists()) {
			file.getParentFile().mkdirs();
		}
		FileWriter fw = new FileWriter(file);

		Document doc = Jsoup.connect(url).get();
		// logger.info(doc.html());
		fw.write(doc.html());
		fw.close();
	}

	public void readHomePageTxt(String path, String url) throws Exception {
		String title = "";
		String content = "";
		List<String> imgList = Lists.newArrayList();
		Document doc = null;
		if (StringUtils.isNotBlank(path)) {
			doc = Jsoup.parse(new File(path), "UTF-8");
		} else if (StringUtils.isNotBlank(url)) {
			doc = Jsoup.connect(url).timeout(5000).get();
		}
		Elements divs = doc.select(".blockcode");
		if (divs.size() == 2) {
			Element divTitle = divs.get(0);
			title = divTitle.text();
			Element divContent = divs.get(1);
			Elements lis = divContent.select("li");
			if (CollectionUtils.isNotEmpty(lis)) {
				for (Element li : lis) {
					String text = li.text();
					if (StringUtils.isNotBlank(text)) {
						if (text.startsWith("[img]")) {
							text = text.replace("[img]", "");
							text = text.replace("[/img]", "");
							imgList.add(text);
						} else if(text.startsWith("http://img")){
							imgList.add(text);
						}else {
							text = text.replaceAll("\\[color=\\w*\\]", "");
							text = text.replaceAll("\\[size=\\w*\\]", "");
							text = text.replace("[b]", "");
							text = text.replace("[/b]", "");
							text = text.replace("[/color]", "");
							text = text.replace("[/size]", "");
							text = text.replace("[url=", "");
							text = text.replace("[/url]", "");
							content += text + "\r\n";
						}
					}
				}
			}
		}


		System.out.println("=============title: " + title);
		System.out.println("=============content: " + content);
		// System.out.println(content.length());
		System.out.println("=============imgList: " + imgList);
		
		String torrentUrl = "";
		Elements torrentLink = doc.select("ignore_js_op>span>a");
		if(torrentLink.size()==0){
			torrentLink = doc.select("ignore_js_op").select("a");
			System.out.println("=============torrentName: " + torrentLink.text());
			Elements script = doc.select("ignore_js_op").select("script");
			torrentUrl = torrentLink.attr("abs:href").replace(torrentLink.attr("href"), "")+ script.html().substring(script.html().indexOf("href=\"")+"href=\"".length(), script.html().indexOf("\";"));
			System.out.println("=============torrentUrl: " + torrentUrl);
		}else{
			torrentUrl = torrentLink.attr("abs:href");
			System.out.println("=============torrentUrl: " + torrentUrl);
			// System.out.println();
			// http://www.lwgod.com/dxksst_download-download1.html?inf=YXR0YWNobWVudHxNVEUyTnpjMU1YdzRNV1l6TTJZeFpud3hOVEExTURNME5EazNmREI4T0RFMU9ETXp8dG9ycmVudHwyODc5MHwyNDk5OHwlQzMlQ0UlQkIlQzMlQ0MlRUMlQ0MlQzMlQTElQTQlQzElRkElQ0QlRjglMjhMV2dvZC5jb20lMjkuNzIwcC4lRDElQzclQzklQUElQ0QlRjUlQTMlQkElQjYlQjclQ0ElREUlRDUlRjklQjAlRDQuJUQxJUM3JUM5JUFBJUEzJUJBJUNEJUY1JUQ1JURGJUQ2JUFFJUJEJUEzLnRvcnJlbnR8MHw=

			
			// this.readTorrentUrl(, );
		}
		Document torrentDoc = Jsoup.connect(torrentUrl).get();
		Elements torrentLinkReal = torrentDoc.select(".dxksst>div>p>a");
		System.out.println("=============torrentName: " + torrentDoc.select(".dxksst>div>p>font").text());
		System.out.println("=============torrentUrlReal: " + torrentLinkReal.attr("abs:href"));
	}

	private File readTorrentUrl(String fileName, String torrentUrl) throws Exception {
		InputStream is = null;
		FileOutputStream out = null;
		File file = null;
		try {
			URL url = new URL(torrentUrl);
			URLConnection conn = url.openConnection();
			conn.setConnectTimeout(5000);
			conn.setReadTimeout(1000);

			byte[] buffer = new byte[0];
			int count = 0;
			while (buffer.length == 0 || count < 10000) {
				count++;
				is = conn.getInputStream();
				buffer = new byte[is.available()];
			}

			String contractDownload = "D:";
			file = new File(contractDownload + "/" + fileName);
			if (!file.exists()) {
				file.createNewFile();
			}
			out = new FileOutputStream(file);

			int c;
			while ((c = is.read(buffer)) != -1) {
				// System.out.println("c:" + c);
				out.write(buffer, 0, c);
				// Thread.sleep(100);
			}
		} catch (IOException e) {
			throw e;
		} finally {
			if (is != null) {
				is.close();
			}
			if (out != null) {
				out.close();
			}
		}
		return file;
	}

}
